package com.ppx.life.service.impl;

import com.ppx.life.common.exception.ServiceException;
import com.ppx.life.dao.User;
import com.ppx.life.dao.UserExample;
import com.ppx.life.dao.vo.DataObject;
import com.ppx.life.mapping.UserMapper;
import com.ppx.life.service.UserService;
import com.ppx.life.utility.Utill;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired

    private UserMapper userMapper;

    @Override
    public DataObject register(User user) {
        //1.判断参数
        if(user.getSerialNum()==null){
            throw  new IllegalArgumentException("参数异常");
        }
        if (user.getPwd()==null) throw new ServiceException("请输入密码");
        //生成一个token
        String accessToken = Utill.getRandomString(32);
        user.setAccessToken(accessToken);
        //判断是否存在该用户
        if(userMapper.selectIdBySerialNum(user.getSerialNum())!=null){
            throw new ServiceException("该用户已注册，请直接登录");
        }
        //向user表长插入数据
        try {
            userMapper.insert(user);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("系统故障,注册失败");
        }
        //查询该用户的信息，并响应给客户端
        return userMapper.selectBySerialNum(user.getSerialNum());
    }

    @Override
    public Integer selectBySerialNum(String serialNum) {
        return null;
    }

    @Override
    public DataObject loginCheck(User user) {
        //1.判断参数
        if(user.getId()==0){
            throw new IllegalArgumentException("参数异常");
        }
        if(user.getId()==null||user.getPwd()==null){
            throw new IllegalArgumentException("参数异常");
        }
        UserExample userExample = new UserExample();
        userExample.createCriteria().andPwdEqualTo(user.getPwd()).andIdEqualTo(user.getId());
        //查询用户
        if (userMapper.selectByExample(userExample).size()<=0) {
            throw new ServiceException("用户名或密码错误");
        }
        //更新token
        String token = Utill.getRandomString(32);
        user.setAccessToken(token);
        //更新token
        try{
            userMapper.updateAccessToken( token,user.getId());
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("系统故障,登录失败");
        }

        return userMapper.selectDataObjectById(user.getId());
    }

}
